package com.example.foodsy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.foodsy.utils.JwtUtils;
import com.example.foodsy.utils.Result;
import com.example.foodsy.entity.Admin;
import com.example.foodsy.mapper.AdminMapper;
import com.example.foodsy.service.AdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 系统管理员表 服务实现类
 * </p>
 *
 * @author cgc
 * @since 2025-09-23
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 管理员登录（验证密码）
     */
    @Override
    public Result getAdminByNameByPass(String adminName, String adminPassword) {
        // 1. 根据用户名查询管理员
        LambdaQueryWrapper<Admin> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Admin::getAdminName, adminName);
        Admin admin = getOne(wrapper);

        // 2. 校验管理员是否存在
        if (admin == null) {
            return Result.fail("管理员不存在");
        }

        // 3. 验证密码（核心：用BCrypt比对明文与加密后的密码）
        boolean passwordMatch = passwordEncoder.matches(adminPassword, admin.getAdminPassword());
        if (!passwordMatch) {
            return Result.fail("密码错误");
        }

        // 4. 登录成功（后续会生成JWT令牌）
        return Result.ok(admin);
    }

    @Override
    public Result addAdmin(Admin admin) {
        // 1. 校验必要参数
        if (admin == null || !StringUtils.hasText(admin.getAdminName()) || !StringUtils.hasText(admin.getAdminPassword())) {
            return Result.fail("管理员名称或密码不能为空");
        }
        try {
            // 密码加密处理
            String encodedPassword = passwordEncoder.encode(admin.getAdminPassword());
            admin.setAdminPassword(encodedPassword);

            boolean success = save(admin);
            return success ? Result.ok() : Result.fail("新增管理员失败");
        } catch (Exception e) {
            return Result.fail("新增管理员异常：" + e.getMessage());
        }
    }

    @Override
    public Result deleteAdmin(Long id) {
        try {
            boolean success = removeById(id);
            return success ? Result.ok() : Result.fail("删除管理员失败");
        } catch (Exception e) {
            return Result.fail("删除管理员异常：" + e.getMessage());
        }
    }

    @Override
    public Result updateAdmin(Admin admin) {
        try {
            // 如果修改了密码，则重新加密
            if (StringUtils.hasText(admin.getAdminPassword())) {
                String encodedPassword = passwordEncoder.encode(admin.getAdminPassword());
                admin.setAdminPassword(encodedPassword);
            }

            boolean success = updateById(admin);
            return success ? Result.ok() : Result.fail("修改管理员失败");
        } catch (Exception e) {
            return Result.fail("修改管理员异常：" + e.getMessage());
        }
    }

    @Override
    public Result getAdminById(Long id) {
        try {
            Admin admin = getById(id);
            return admin != null ? Result.ok(admin) : Result.fail("未找到该管理员");
        } catch (Exception e) {
            return Result.fail("查询管理员异常：" + e.getMessage());
        }
    }

    @Override
    public Result getAdminList(Integer pageNum, Integer pageSize, String username) {
        try {
            // 构建分页对象
            Page<Admin> page = new Page<>(pageNum, pageSize);

            // 构建查询条件
            LambdaQueryWrapper<Admin> wrapper = new LambdaQueryWrapper<>();
            if (StringUtils.hasText(username)) {
                wrapper.like(Admin::getAdminName, username);
            }

            // 执行分页查询
            Page<Admin> adminPage = page(page, wrapper);

            return Result.ok(adminPage);
        } catch (Exception e) {
            return Result.fail("查询管理员列表异常：" + e.getMessage());
        }
    }
}
